package org.example.commerce.imp.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.xpath.internal.operations.Or;
import lombok.extern.slf4j.Slf4j;
import org.example.commerce.api.beans.CreateNewGoodsParam;
import org.example.commerce.api.beans.ModifyGoodsParam;
import org.example.commerce.api.beans.OrderParam;
import org.example.commerce.dao.GoodsMapper;
import org.example.commerce.dao.entity.Goods;
import org.example.commerce.dao.vo.ProduceWithCategoryVo;
import org.example.commerce.imp.service.GoodsService;
import org.example.common.enums.BusinessErrorCode;
import org.example.common.exception.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public PageInfo<ProduceWithCategoryVo> selectAll(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<ProduceWithCategoryVo> list = goodsMapper.selectProduceWithCategory();
        PageInfo<ProduceWithCategoryVo> result = new PageInfo<>(list);
        return result;
    }

    @Override
    public Goods updateGoods(ModifyGoodsParam request) {
        Goods goods = goodsMapper.selectByPrimaryKey(request.getId());
        if (goods==null){
            throw  new BusinessException(BusinessErrorCode.Goods_NOT_FOUND);
        }
        BeanUtils.copyProperties(request, goods);
        if(goodsMapper.updateByPrimaryKey(goods)!=1){
            throw new BusinessException(BusinessErrorCode.UNKNOWN_ERROR);
        }
        return goods;
    }

    @Override
    public Goods addGoods(CreateNewGoodsParam request) {
        Goods goods = Goods.builder()
                .name(request.getName())
                .price(request.getPrice())
                .createTime(request.getCreateTime())
                .imgUrl(request.getImgUrl())
                .categoryId(request.getCategoryId())
                .build();
        goodsMapper.insert(goods);

        return goods;
    }

    @Override
    public String deleteGoodsById(Long id) {
        int i = goodsMapper.deleteByPrimaryKey(id);
        if (i == 0){
            throw  new BusinessException(BusinessErrorCode.Goods_NOT_FOUND);
        }
        return "删除成功";
    }

    @Override
    public Goods selectGoodsById(Long id) {
        return goodsMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Goods> loadGoods(List<Long> ids) {
        Example example = new Example(Goods.class);
        example.createCriteria().andIn("id",ids);
        return  goodsMapper.selectByExample(example).stream().collect(Collectors.toList());
    }

}
